package com.unohacha.qqj.fzdr.main.sends;

import android.content.Intent;
import android.graphics.Color;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.qpg.superhttp.SuperHttp;
import com.qpg.superhttp.callback.SimpleCallBack;
import com.qpg.superhttp.request.UploadRequest;
import com.qpg.widget.common.ToastUtil;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.adapter.LabelCategaryAdapter;
import com.unohacha.qqj.fzdr.adapter.imgpicker.FabricImagePickerAdapter;
import com.unohacha.qqj.fzdr.bean.BaseBean;
import com.unohacha.qqj.fzdr.bean.CatData;
import com.unohacha.qqj.fzdr.bean.ImgBean;
import com.unohacha.qqj.fzdr.bean.LabelBean;
import com.unohacha.qqj.fzdr.bean.PublishTip;
import com.unohacha.qqj.fzdr.ui.activity.PubSettlementActivity;
import com.unohacha.qqj.fzdr.util.GlideImageLoaderForPicker;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.view.FullyGridLayoutManager;
import com.unohacha.qqj.fzdr.view.MyGridView;
import com.unohacha.qqj.mylibrary.base.BaseActivity;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 其他供求
 */
public class SendOtherSupplyActivity extends BaseActivity implements FabricImagePickerAdapter.OnRecyclerViewItemClickListener{
    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    TextView commonTitle;
    @BindView(R.id.common_right_image)
    ImageView commonRightImage;
    @BindView(R.id.common_right_text)
    TextView commonRightText;
    @BindView(R.id.et_title)
    EditText etTitle;
    @BindView(R.id.ll_classify)
    LinearLayout llClassify;
    @BindView(R.id.ll_label)
    LinearLayout llLabel;
    @BindView(R.id.et_format)
    EditText etFormat;
    @BindView(R.id.et_number)
    EditText etNumber;
    @BindView(R.id.et_koufu)
    EditText etKoufu;
    
    @BindView(R.id.recycler)
    RecyclerView recyclerView;
    @BindView(R.id.bt_next)
    Button btNext;
    @BindView(R.id.tv_type)
    TextView tvType;
    @BindView(R.id.tv_label_count)
    TextView tvLabelCount;
    @BindView(R.id.gv_sing_style)
    MyGridView gridView;
    @BindView(R.id.et_extra)
    EditText etTxtra;
    LabelCategaryAdapter labelCategaryAdapter;
    @BindView(R.id.tv_mi)
    TextView tv_mi;
    @BindView(R.id.one_price_tv)
    TextView one_price_tv;

    private OptionsPickerView pvOptionsType;
    private String fabricName,fabricId;
    ArrayList<CatData.Two> listsDetial;
    ArrayList<PublishTip> listsCateName;
    ArrayList<LabelBean> listLabel;
    List<CatData> listTwo;
    HashMap<String,String> map;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private FabricImagePickerAdapter imagePickerAdapter;
    public static ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 9;               //允许选择图片最大数
    private String mainId="";
    
    private String[] mTitles;//标题的提示的数组
    private String[] mSpecs;//规格的提示数组
    private String[] mContents;//其他内容提示数组
    private String[] mNumberss;//产品数量的数组
    private String[] mNumUnits ;//数量单位的数组
    private String[] mOnePrices;//单价提示的数组
    private String[] mOnePriceUnits;//单价单位的数组
    private int type = 1;//1供应 2 需求
    
    
    @Override
    protected int getLayoutId() {
        return R.layout.activity_supply_other;
    }
    
    @Override
    protected void initView() {
        commonRightImage.setVisibility(View.INVISIBLE);
        commonTitle.setText("其他供应");
        map=new HashMap<>();
        mainId=getIntent().getStringExtra("main_id");
        type = getIntent().getIntExtra("type",0);
        fabricName=getIntent().getStringExtra("name");
        fabricId=getIntent().getStringExtra("id");
        tvType.setText(fabricName);
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        listTwo=new ArrayList<>();
        initImagePicker();
        selImageList = new ArrayList<>();
        imagePickerAdapter = new FabricImagePickerAdapter(this, selImageList, maxImgCount);
        imagePickerAdapter.setOnItemClickListener(this);

        recyclerView.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(imagePickerAdapter);
        pvOptionsType = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvType.setText(listsDetial.get(options1).getName());
            }
        }).setContentTextSize(20)//设置滚轮文字大小
                .setDividerColor(Color.LTGRAY)//设置分割线的颜色
                .setSelectOptions(0)//默认选中项
                .setBgColor(Color.WHITE)
                .setTitleBgColor(Color.WHITE)
                .setTitleColor(Color.LTGRAY)
                .setCancelColor(Color.GRAY)
                .setSubmitColor(Color.RED)
                .setSubmitText("完成")
                .setTextColorCenter(Color.BLACK)
                .isCenterLabel(true) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setBackgroundId(0x66000000) //设置外部遮罩颜色
                .build();
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                labelCategaryAdapter.chiceState(position);
                tvLabelCount.setText(labelCategaryAdapter.getSelectCount()+"个");
            }
        });
        getLabelData();
        getTips();
    }

    @OnClick({R.id.ll_classify, R.id.ll_label, R.id.bt_next,
            R.id.common_back,R.id.tv_type,R.id.tv_mi,
            R.id.one_price_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_classify:
                break;
                
            case R.id.ll_label:
                break;
            case R.id.ll_select_num:
                break;

            case R.id.tv_type:
                break;
            case R.id.bt_next:
                if(TextUtils.isEmpty(etTitle.getText())){
                    ToastUtil.showCustomToast("请填写标题");
                    return;
                }
                if(TextUtils.isEmpty(etTxtra.getText())){
                    ToastUtil.showCustomToast("请填写补充说明!");
                    return;
                }
                if(etFormat.getText().length()==0){
                    ToastUtil.showCustomToast("请填写规格!");
                    return;
                }
                if(etNumber.getText().length()==0){
                    ToastUtil.showCustomToast("请填写产品数量!");
                    return;
                }
                if(etKoufu.getText().length()==0){
                    ToastUtil.showCustomToast("请填写单价!");
                    return;
                }
                
                String location=Prefer.obtainReLocation(SendOtherSupplyActivity.this);
                map.put("token",Prefer.getInstance().getToken());
                map.put("title",etTitle.getText().toString().trim());
                map.put("supply_cate_id",fabricId);
                map.put("typeid","1");

                map.put("price",etKoufu.getText().toString().trim());
                map.put("price_company","");
                map.put("spec",etFormat.getText().toString().trim());
                map.put("nums",etNumber.getText().toString().trim());
                map.put("nums_company","");
                map.put("content",etTxtra.getText().toString().trim());
//                map.put("breadth_company","");
//                map.put("technology","");
//                map.put("breadth_company","");
//                map.put("gram_weight_company","");
//                map.put("fabric_model",etFormat.getText().toString().trim());
                mSubmit(map);
                break;
            case R.id.common_back:
                finish();
                break;
            case R.id.tv_mi://数量单位的弹窗
                showJobPickciew(mNumUnits,1);
                break;
            case R.id.one_price_tv://单价的规格的弹窗
                showJobPickciew(mOnePriceUnits,2);
                break;
        }
    }

    /**
     * 产品数量或产品单价的弹窗
     */
    private void showJobPickciew(final String[] mCateList, final int type) {
        if (mCateList.length == 0) {
            MyToast("暂无可选项目");
            return;
        }
        List<String> list = new ArrayList<>();
        for (int i = 0; i < mCateList.length; i++) {
            list.add(mCateList[i]);
        }
        OptionsPickerView pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                
             String companyType = mCateList[options1];
                if (type == 1) {
                    tv_mi.setText(mCateList[options1]);
                }else {
                    one_price_tv.setText(mCateList[options1]);
                }
            }
        })

                .setTitleBgColor(Color.WHITE)//标题背景颜色 Night mode
                .setTitleColor(getResources().getColor(R.color.text))//标题文字颜色)//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.blue))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.black))//取消按钮文字颜色.build();
                .setCyclic(false, false, false)
                .build();
        pvOptions.setPicker(list);//一级选择器
        pvOptions.show();
    }
    
    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoaderForPicker());   //设置图片加载器
        imagePicker.setShowCamera(true);                      //显示拍照按钮
        imagePicker.setCrop(true);                           //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true);                   //是否按矩形区域保存
        imagePicker.setSelectLimit(maxImgCount);              //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);                       //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);                      //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);                         //保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);                         //保存文件的高度。单位像素
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent1 = new Intent(SendOtherSupplyActivity.this, ImageGridActivity.class);
                startActivityForResult(intent1, REQUEST_CODE_SELECT);

                break;
//            default:
//                //打开预览
//                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
//                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
//                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
//                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
//                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
//                break;
        }
    }
    ArrayList<ImageItem> images = null;
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null) {
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                if (images != null) {
                    selImageList.clear();
                    selImageList.addAll(images);
                    imagePickerAdapter.setImages(selImageList);
                }
            }
        }
    }

    private void getLabelData(){
        String token=Prefer.getInstance().getToken();
        SuperHttp.post("api/supplyinfo/supplyLabelMatching")
                .addParam("supply_cate_id",mainId )
                .request(new SimpleCallBack<BaseBean<ArrayList<LabelBean>>>() {
                    @Override
                    public void onSuccess(BaseBean<ArrayList<LabelBean>> data) {
                        if(data.getCode()==0){
                            //   ToastUtil.showCustomToast("暂无数据");
                            return;
                        }
                        listLabel=new ArrayList<>();
                        listLabel.addAll(data.getData());

                        labelCategaryAdapter=new LabelCategaryAdapter(SendOtherSupplyActivity.this,listLabel);
                        gridView.setAdapter(labelCategaryAdapter);
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });
    }

    //获取供求默认提示
    private void getTips(){
        String token=Prefer.getInstance().getToken();
        SuperHttp.post("api/supplyinfo/supplyPrompt")
                .addParam("supply_cate_id",fabricId )
                .request(new SimpleCallBack<BaseBean<ArrayList<PublishTip>>>() {
                    @Override
                    public void onSuccess(BaseBean<ArrayList<PublishTip>> data) {
                        
                        if(data.getCode()==0){
                            //   ToastUtil.showCustomToast("暂无数据");
                            return;
                        }
                        
                        listsCateName = new ArrayList<>();
                        listsCateName.addAll(data.getData());
                        setLableName();
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                    }
                });
    }

    //设置供求默认提示
    private void setLableName(){
        if (0 != listsCateName.size()){
            for (int i = 0; i < listsCateName.size(); i++) {
                if ("101".equals(listsCateName.get(i).getId())){//规格
                    mSpecs = listsCateName.get(i).getPrompt();
                }
                
                if ("102".equals(listsCateName.get(i).getId())){//补充说明
                    mContents = listsCateName.get(i).getPrompt();
                }
                if ("100".equals(listsCateName.get(i).getId())){//单价单位
                    mOnePriceUnits = listsCateName.get(i).getPrompt();
                }
                if ("99".equals(listsCateName.get(i).getId())){//单价的提示
                    mOnePrices = listsCateName.get(i).getPrompt();
                }
                
                if ("98".equals(listsCateName.get(i).getId())){//数量单位
                    mNumUnits = listsCateName.get(i).getPrompt();
                }
                if ("97".equals(listsCateName.get(i).getId())){//数量
                    mNumberss = listsCateName.get(i).getPrompt();
                }
                if ("96".equals(listsCateName.get(i).getId())){//标题
                    mTitles = listsCateName.get(i).getPrompt();
                }
            }
            
            etTitle.setHint(mTitles[0]);
            etFormat.setHint(mSpecs[0]);
            etNumber.setHint(mNumberss[0]);
            etKoufu.setHint(mOnePrices[0]);
            etTxtra.setHint(mContents[0]);
            tv_mi.setText(mNumUnits[0]);
            one_price_tv.setText(mOnePriceUnits[0]);
        }
    }

    
    private void mSubmit(final HashMap<String,String> map){
        showLoading();
        Intent intent = new Intent(this,PubSettlementActivity.class);
        intent.putExtra("params", map);
        intent.putExtra("type",type);
        startActivity(intent);
        hideLoading();
    }
}
